package project

import (
	"fmt"
	"github.com/xbitgo/core/tools/tool_str"
	"go/format"
	"golang.org/x/tools/imports"
	"regexp"
	"strings"
)

func parseFieldTagMap(tag string) map[string]string {
	tagParts := strings.Split(tag, "\" ")
	result := map[string]string{}
	for _, parts := range tagParts {
		pairs := strings.SplitN(parts, ":", 2)
		if len(parts) < 2 {
			continue
		}
		result[pairs[0]] = strings.Trim(pairs[1], "\"")
	}
	return result
}

func AddEntityPkg(str string) string {
	for i, r := range []rune(str) {
		if tool_str.UFirst(string(r)) {
			return str[:i] + "entity." + str[i:]
		}
	}
	return str
}

func (a *App) format(buf []byte, filename string) []byte {
	buf2, err := format.Source(buf)
	if err == nil {
		buf = buf2
	}
	buf3, err := imports.Process(filename, buf, nil)
	if err == nil {
		buf = buf3
	}
	return buf
}

func (a *App) formatOnly(buf []byte) []byte {
	buf2, err := format.Source(buf)
	if err == nil {
		buf = buf2
	}
	return buf
}

func (a *App) GenFileHeader(pkg string, imports []string) []byte {
	importStr := ""
	for _, i := range imports {
		importStr += fmt.Sprintf(`"%s"`+"\n", i)
	}
	bufH := fmt.Sprintf(`// Code generated by go3gen. DO NOT EDIT.
package %s

import (
%s
)`, pkg, importStr)
	return []byte(bufH)
}

func (a *App) GenFileHeaderWithAsName(pkg string, imports []string, importAs map[string]string) []byte {
	importStr := ""
	for _, i := range imports {
		importStr += fmt.Sprintf(`"%s"`+"\n", i)
	}
	for name, i := range importAs {
		importStr += fmt.Sprintf(`%s "%s"`+"\n", name, i)
	}
	bufH := fmt.Sprintf(`// Code generated by go3gen. DO NOT EDIT.
package %s

import (
%s
)`, pkg, importStr)
	return []byte(bufH)
}

func (a *App) GenFileHeaderAllowEdit(pkg string, imports []string) []byte {
	importStr := ""
	for _, i := range imports {
		importStr += fmt.Sprintf(`"%s"`+"\n", i)
	}
	bufH := fmt.Sprintf(`
package %s

import (
%s
)`, pkg, importStr)
	return []byte(bufH)
}

var microExp = regexp.MustCompile("@MICRO\\[([\\w|,]+)]")

func (a *App) MicroParse(doc string) []string {
	r := microExp.FindStringSubmatch(doc)
	if len(r) > 1 {
		return strings.Split(r[1], ",")
	}
	return nil
}
